package net.esj.basic.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.esj.basic.utils.Validators;

public class StaticHtmlServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8490848420694552905L;

	private String url;

	private String realPath;// 文件保存路径

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path = req.getParameter("path");// 访问地址路径
		String fileName = req.getParameter("fileName");// 保存的文件名及相对路径
		String charset = req.getParameter("charset");//保存文件之编码
		if(Validators.isEmpty(charset)){
			charset = "UTF-8";
		}
		
		//path = url + "/" + path;
		fileName = realPath + File.separator + fileName;

		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(path);

		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		final ServletOutputStream stream = new ServletOutputStream() {
			public void write(byte[] data, int offset, int length) {
				os.write(data, offset, length);
			}

			public void write(int b) throws IOException {
				os.write(b);
			}
		};

		final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
		HttpServletResponse rep = new HttpServletResponseWrapper(resp) {
			public ServletOutputStream getOutputStream() {
				return stream;
			}

			public PrintWriter getWriter() {
				return pw;
			}
		};
		rd.include(req, rep);
		pw.flush();
		FileOutputStream fos = new FileOutputStream(fileName); // 把jsp输出的内容写到xxx.htm
		fos.write(os.toString().getBytes(charset));//转码
		//os.writeTo(fos);
		fos.close();
		//PrintWriter out = resp.getWriter();
		//out.print("<p align=center><font size=3 color=red>success！</font></p>");

	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setRealPath(String realPath) {
		this.realPath = realPath;
	}

}
